const router = require('koa-router')();
// const request = require('../lib/request');
const crypto = require('crypto');
const { v4: uuidv4 } = require('uuid');
const { generateSalt } = require('../lib/utils');

// 用户登录，首先获取openid和session，存储session相关信息，用于维护用户登录信息。
// 判断用户是否存在，存在则返回加密后的session和用户信息，否则返回需要注册的返回码
router.post('/api/login', async (ctx, next) => {
  // 通过小程序传递的code，访问微信服务器，获取session_id和openid
  const {
    body: { code, studentID, password },
  } = ctx.request;

  try {
    const errRet = {
      code: -1,
      message: '学号或者密码输入错误',
    };

    /* 判断用户是否登录成功 */
    // 判断用户是否存在'

    const user = await global._db.model.student.getUser(studentID);
    if (!user) {
      // 用户不存在
      ctx.body = errRet;
      return;
    }
    console.log('user::', user);

    const { Sname, Stel, Spwd, Salt } = user;

    // 判断密码是否正确
    const userPass = password + Salt;
    const md5 = crypto.createHash('md5');
    md5.update(userPass);
    const encryptPwd = md5.digest('hex');
    if (encryptPwd === Spwd) {
      // 密码正确
      // uuid生成session_id返回给小程序
      const sessionId = uuidv4();
      console.log('sessionid::', sessionId);
      const time = 1000 * 86400 * 90;
      ctx.session = {
        sessionId,
        studentID,
        name: Sname,
        phone: Stel,
        expireTime: Date.now() + time, // 3个月有效期
      };
      ctx.body = {
        code: 0,
        message: 'success',
        data: {
          phone: Stel,
          name: Sname,
          sessionId,
        },
      };
      return;
    }
    ctx.body = errRet;
  } catch (error) {
    global._logger.error('login error::', error);
    ctx.body = errRet;
  }
});

// 用户注册
router.post('/api/register', async (ctx, next) => {
  const {
    body: { code, name, phone, studentID, password },
  } = ctx.request;
  try {
    // 判断该学号是否已经注册
    const user = await global._db.model.student.getUser(studentID);
    if (user) {
      ctx.body = {
        code: -1,
        message: '该学号已注册',
      };
      return;
    }

    // 对密码二次加密
    const salt = generateSalt(8);
    const userPass = password + salt;
    const md5 = crypto.createHash('md5');
    md5.update(userPass);
    const encryptPwd = md5.digest('hex');

    await global._db.model.student.insertUser({
      id: uuidv4(), 
      Sno: studentID,
      Stel: phone,
      Spwd: encryptPwd,
      Salt: salt,
      Sname: name,
    });
    ctx.body = {
      code: 0,
      message: '注册用户成功',
    };
  } catch (error) {
    global._logger.error('register error::', error);
    ctx.body = {
      code: -1,
      message: '注册用户失败',
    };
  }
});

// 获取用户信息
router.get('/api/getUser', async (ctx, next) => {
  const session = ctx.session || {};
  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      studentID: session.studentID,
      name: session.name,
      phone: session.phone,
    },
  };
});

// 更新手机号
router.post('/api/resetPhone', async (ctx, next) => {
  const {
    body: { phone, password },
  } = ctx.request;
  try {
    const { studentID } = ctx.session || {};
    const errRet = {
      code: -1,
      message: '手机号码或密码输入错误',
    };

    // 判断用户是否存在'
    const user = await global._db.model.student.getUser(studentID);
    if (!user) {
      // 用户不存在
      ctx.body = errRet;
      return;
    }
    console.log('user::', user);
    const { Spwd, Salt } = user;
    // 判断密码是否正确
    const userPass = password + Salt;
    const md5 = crypto.createHash('md5');
    md5.update(userPass);
    const encryptPwd = md5.digest('hex');
    if (encryptPwd === Spwd) {
      // 密码正确, 更新手机号
      await global._db.model.student.updateUser({ Stel: phone }, studentID);
      ctx.body = {
        code: 0,
        message: '修改手机号成功',
      };
      return;
    }

    ctx.body = errRet;
  } catch (error) {
    global._logger.error('resetPhone error::', error);
    ctx.body = {
      code: -1,
      message: '修改手机号失败',
    };
  }
});

// 更新密码
router.post('/api/resetPassword', async (ctx, next) => {
  const {
    body: { newPwd, oldPwd },
  } = ctx.request;
  try {
    const { studentID } = ctx.session || {};
    const errRet = {
      code: -1,
      message: '密码输入错误',
    };

    // 判断用户是否存在'
    const user = await global._db.model.student.getUser(studentID);
    if (!user) {
      // 用户不存在
      ctx.body = errRet;
      return;
    }
    console.log('user::', user);
    const { Spwd, Salt } = user;
    // 判断密码是否正确
    const userPass = oldPwd + Salt;
    const md5 = crypto.createHash('md5');
    md5.update(userPass);
    const encryptPwd = md5.digest('hex');
    if (encryptPwd === Spwd) {
      // 密码正确, 更新密码
      const nSalt = generateSalt(8);
      const nUserPass = newPwd + nSalt;
      const md5 = crypto.createHash('md5');
      md5.update(nUserPass);
      const nEncryptPwd = md5.digest('hex');

      await global._db.model.student.updateUser({ Spwd: nEncryptPwd, Salt: nSalt }, studentID);
      ctx.body = {
        code: 0,
        message: '修改密码成功',
      };
      return;
    }

    ctx.body = errRet;
  } catch (error) {
    global._logger.error('resetPassword error::', error);
    ctx.body = {
      code: -1,
      message: '修改密码失败',
    };
  }
});

module.exports = router;
